var read = require('hy5b/backend/read');
var write = require('hy5b/backend/write');

var cpFile = require('cp-file');

var fss = require('fs');

var jsdom = require('jsdom');
var $ = require('jquery');

var pref = './qda2018春波段 新2.files'

var hedui = write('dist.html');

function bu0(num, len) {
  var str = '' + num;
  if (str.length < len) {
    for (var i = str.length; i < len; i++) {
      str = '0' + str;
    }
  }
  return str;
}

var uniq = {}
 
read.readFile(pref + '/sheet002.htm', function(err, html) {
    if (err) {
      console.error(err)
      return
    }

    jsdom.env(
      html,
      ["http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"],
      function (errors, window) {
        var $ = window.$;
        var $table = $('body>table')

        hedui.write('<!DOCTYPE html>')
        hedui.write('<html>')
        hedui.write('<head><meta charset="utf-8"></head>')
        hedui.write('<body>')

        hedui.write('<table border="1">')

        $table.children('tbody').children('tr').each(function() {
          var name = $(this).children('td').eq(1).text();
          name = name.replace(/[\r\n]*/g, '');

          var img = $(this).children('td').eq(0).find('img');

          if (img.length > 0) {
            var src = img.attr('src');
            var num = parseInt(src.replace('.gif', '').replace('image', '')) - 1;
            var srcFile = pref + '/image' + bu0(num, 3) + '.png';
            
            hedui.write('<tr><td>' + name + '</td><td><img src="dist3/' + name + '.png"></td></tr>');

            if (!uniq[name]) { //只保存第一张照片
              fss.stat(srcFile, function(err, stat) {
                if (err) {
                  return;
                }

                cpFile(srcFile, 'dist/' + name + '.png').then(() => {
                  console.log(srcFile, name)
                }); 
                
              });
              uniq[name] = 1;
            }
          } else if (name) {
            hedui.write('<tr><td>' + name + '</td><td></td></tr>');
          }
        })
        hedui.write('</table>')
        hedui.write('</body>')
        hedui.write('</html>')
      }
    );
}, null, 'gbk');